package de.ret_world.openrpgstudio.editor.gui;

import buoy.event.RepaintEvent;
import buoy.widget.BOutline;
import buoy.widget.BScrollPane;
import buoy.widget.BorderContainer;
import buoy.widget.CustomWidget;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.file.Path;
import javax.imageio.ImageIO;
import org.apache.log4j.Logger;

/**
 * This is a Bouy Widget to show a preview of a image with a few parameters.
 *
 * @author Emu
 */
public class ImagePreviewWidget extends BorderContainer {

    private boolean filled;
    private BufferedImage image;
    private BScrollPane scrl;
    private CustomWidget pane;
    private boolean enabled = true;

    public ImagePreviewWidget(Path image, boolean filled) {
        this(filled);
        setImage(image);
    }

    public ImagePreviewWidget(boolean filled) {
        this.filled = filled;

        pane = new CustomWidget();
        pane.addEventLink(RepaintEvent.class, this, "paintIt");

        if (!filled) {
            scrl = new BScrollPane(pane);
        }

        if (filled) {
            add(BOutline.createBevelBorder(pane, false), CENTER);
        } else {
            add(BOutline.createBevelBorder(scrl, false), CENTER);
        }
    }

    private void paintIt(RepaintEvent ev) {
        Graphics2D g = ev.getGraphics();

        if (image != null && isEnabled()) {
            if (filled) {
                g.drawImage(image, 0, 0, pane.getBounds().width, pane.getBounds().height, null);
            } else {
                g.drawImage(image, 0, 0, null);
                int w = image.getWidth();
                int h = image.getHeight();
                pane.setPreferredSize(new Dimension(w, h));
                scrl.layoutChildren();
            }
        }
    }

    public void setImage(Path image) {
        try {
            this.image = ImageIO.read(image.toFile());
        } catch (IOException ex) {
            Logger.getLogger(ImagePreviewWidget.class).error(ex);
        }
        repaint();
    }

    public Dimension getImageSize() {
        if (image != null) {
            return new Dimension(image.getWidth(), image.getHeight());
        }
        return new Dimension();
    }

    @Override
    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
        pane.repaint();
    }

    @Override
    public boolean isEnabled() {
        return enabled;
    }
}
